<template>
  <div class="wrap">
    <div class="wrap-button" style="height: 32px">
      <a-button style="margin-right: 8px" type="primary" @click="handleAdd" v-if="isManager"
        >新增
      </a-button>
      <!-- <a-button style="margin-right: 8px" type="primary" v-if="isManager">批量导入</a-button>-->
      <a-button
        style="margin-right: 8px"
        type="primary"
        @click="exportStore"
        v-if="!roleList.includes('VISITOR')"
        >导出库存
      </a-button>
      <div style="float: right">
        <a-radio-group
          v-model:value="recordSo.afloatStatus"
          button-style="solid"
          style="margin-right: 8px"
          @change="reload"
        >
          <a-radio-button value="">全部</a-radio-button>
          <a-radio-button value="0">在库</a-radio-button>
          <a-radio-button value="1">在途</a-radio-button>
        </a-radio-group>
        <a-input
          v-model:value="recordSo.keyword"
          style="width: 200px; margin-right: 8px"
          placeholder="输入产品关键字查询"
          allow-clear
          @pressEnter="reload"
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>

        <a-button type="primary" @click="reload">查询</a-button>
      </div>
    </div>
    <div class="wrap-table">
      <!-- <BaseTitle title="用户列表" /> -->
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        size="middle"
        @change="handleTableChange"
        width="300"
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'productName'">
            <a-tag color="#f50" v-if="record.afloatStatus === 1">途</a-tag>
            {{ record.productName }}
          </template>
          <template v-if="!roleList.includes('VISITOR') && column.key === 'operation'">
            <a-button class="button-interval" type="link" size="small" @click="handleLog(record)">
              库存记录
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleOrderLog(record)"
            >
              订单明细
            </a-button>
            <a-button
              v-if="isAdmin || isManager"
              class="button-interval"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              修改
            </a-button>
            <a-button
              v-if="isAdmin"
              class="button-interval"
              type="link"
              size="small"
              @click="handleDelete(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      v-model:visible="open"
      :title="createMode ? '创建产品' : '修改产品'"
      width="680px"
      :bodyStyle="{ padding: '16px 24px 0px 24px' }"
      :centered="false"
      @cancel="handleCloseUpdateProduct"
    >
      <template #footer>
        <a-button key="submit" type="primary" :loading="submitLoading" @click="handleSubmit"
          >提交
        </a-button>
      </template>
      <div>
        <a-form ref="formRef" :model="productBo" name="basic" autocomplete="off">
          <a-row :gutter="8">
            <a-col class="gutter-row" :span="24">
              <a-form-item
                label="产品名称"
                name="productName"
                :rules="[{ required: true, message: '请输入产品名称' }]"
              >
                <a-input v-model:value="productBo.productName" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="有效期" name="limitTime">
                <a-input v-model:value="productBo.limitTime" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="数量" name="storeNum">
                <a-input-number
                  id="inputNumber"
                  v-model:value="productBo.storeNum"
                  :disabled="!createMode && isManager"
                />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="是否在途" name="afloatStatus">
                <a-switch
                  v-model:checked="productBo.afloatStatus"
                  checkedValue="1"
                  unCheckedValue="0"
                  checked-children="是"
                  un-checked-children="否"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-modal>
    <a-modal
      v-model:visible="productLogVisible"
      title="库存日志"
      :width="1200"
      :bodyStyle="{ padding: '16px 24px 0px 24px' }"
      style="padding: 0px 24px"
      @ok="productLogVisible = false"
      :footer="null"
    >
      <a-table
        :columns="productLogColumns"
        :data-source="productLogData"
        size="small"
        :pagination="logPagination"
        @change="handleProductLogChange"
      />
    </a-modal>
    <a-modal
      v-model:visible="orderLogVisible"
      :title="`订单明细`"
      :width="1200"
      :bodyStyle="{ padding: '16px 24px 0px 24px', position: 'relative' }"
      style="padding: 0px 24px"
      @ok="orderLogVisible = false"
      @close="currentProductName = undefined"
      :footer="null"
    >
      <div style="display: flex">
        <a-button type="primary" @click="exportOrderLog">导出</a-button>

        <div style="margin-left: auto; justify-content: flex-end">
          <a-radio-group
            v-model:value="orderLogSo.orderStatus"
            button-style="solid"
            style="margin-right: 8px"
            @change="reloadLog"
          >
            <a-radio-button value="">全部</a-radio-button>
            <a-radio-button value="0" v-if="!isManager">已保存</a-radio-button>
            <a-radio-button value="1">未发货</a-radio-button>
            <a-radio-button value="3">已发货</a-radio-button>
            <a-radio-button value="4">已签收</a-radio-button>
          </a-radio-group>
          <a-range-picker
            style="margin-right: 8px; width: 240px"
            v-model:value="orderTimeRange"
            valueFormat="YYYY-MM-DD"
            @panelChange="reloadLog"
          />
          <a-button type="primary" @click="reloadLog">查询</a-button>
        </div>
      </div>
      <a-table
        :columns="orderLogColumns"
        :data-source="orderLogData"
        size="small"
        style="margin-top: 8px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'afloatStatus'">
            <a-tag color="#f50" v-if="record.afloatStatus === 1">途</a-tag>
            <div v-else></div>
          </template>
          <template v-if="column.key === 'orderStatus'">
            <a-tag v-if="record.orderStatus == 0" color="processing">已保存</a-tag>
            <a-tag v-else-if="record.orderStatus == 1" color="orange">未发货</a-tag>
            <a-tag v-else-if="record.orderStatus == 3" color="green">已发货</a-tag>
            <a-tag v-else-if="record.orderStatus == 4" color="green">已签收</a-tag>
            <a-tag v-else-if="record.orderStatus == 9" color="red">已撤单</a-tag>
            <a-tag v-else color="red">未知</a-tag>
          </template>
        </template>
      </a-table>
      <span
        style="
          line-height: 31px;
          margin-left: 8px;
          font-size: 16px;
          position: absolute;
          bottom: 14px;
        "
        >销售数量：{{ dataQty }}</span
      >
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive, onMounted, nextTick } from 'vue'
  import moment from 'moment'
  import {
    pageProduct,
    createProduct,
    updateProduct,
    deleteProduct,
    exportStoreApi,
    pageProductLogApi,
    watchProduct,
    unwatchProduct,
    currentProduct,
  } from '/@/api/product'
  import { exportLogByProduct, orderLog } from '/@/api/order'
  import {
    ProductVO,
    ProductBO,
    ProductSo,
    ProductLogVO,
    ProductLogSO,
  } from '/@/api/product/model/productModel'
  import { BasicQueryModel } from '/@/api/model/baseModel'
  import { SearchOutlined } from '@ant-design/icons-vue'
  import { useUserStore } from '/@/store/modules/user'
  import type { FormInstance, TableColumnType } from 'ant-design-vue'
  import { message, Modal } from 'ant-design-vue'
  import { exportCheckedOrder } from '/@/api/order'
  import { OrderLogVO, OrderLogSO } from '/@/api/order/model/orderModel'

  const formRef = ref<FormInstance>()
  const userStore = useUserStore()
  const isManager = userStore.getManager
  const isAdmin = userStore.getAdmin
  const roleList = userStore.getRoleList

  const loading = ref(false)
  const open = ref(false)
  const orderLogVisible = ref(false)
  const createMode = ref(true)
  const submitLoading = ref(false)
  const productLogVisible = ref(false)
  const sortedInfo = ref()
  type RangeValue = [string, string]
  const orderTimeRange = ref<RangeValue>()
  const currentProductName = ref<string | undefined>('')
  const currentProductId = ref<string | undefined>('')
  const columns = computed<TableColumnType[]>(() => {
    const sorted = sortedInfo.value || {}
    return [
      {
        title: '产品名称',
        dataIndex: 'productName',
        key: 'productName',
        align: 'center',
        sorter: (a: ProductVO, b: ProductVO) => a.productName.localeCompare(b.productName),
        sortOrder: sorted.columnKey === 'productName' && sorted.order,
      },
      {
        title: '有效期',
        dataIndex: 'limitTime',
        key: 'limitTime',
        align: 'center',
        width: 200,
        sorter: (a: ProductVO, b: ProductVO) => {
          a.limitTime.localeCompare(b.limitTime)
        },
        sortOrder: sorted.columnKey === 'limitTime' && sorted.order,
      },
      {
        title: '系统库存数量',
        dataIndex: 'storeNum',
        key: 'storeNum',
        align: 'center',
        width: 160,
        sorter: (a: ProductVO, b: ProductVO) => a.storeNum - b.storeNum,
        sortOrder: sorted.columnKey === 'storeNum' && sorted.order,
      },
      // {
      //   title: '实物库存数量',
      //   dataIndex: 'actualStoreNum',
      //   key: 'actualStoreNum',
      //   align: 'center',
      //   width: 160,
      // },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        align: 'center',
        width: 160,
        sorter: (a: ProductVO, b: ProductVO) => moment(a.createTime).isAfter(moment(b.createTime)),
        sortOrder: sorted.columnKey === 'createTime' && sorted.order,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        align: 'center',
        width: 280,
      },
    ]
  })

  const productLogData = ref<ProductLogVO[]>([])

  const productLogColumns = [
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      align: 'center',
    },
    {
      title: '操作类型',
      dataIndex: 'operationType',
      key: 'operationType',
      align: 'center',
      width: 120,
    },
    {
      title: '更新数量',
      dataIndex: 'quantity',
      key: 'quantity',
      align: 'center',
      width: 130,
    },
    {
      title: '更新后库存',
      dataIndex: 'storeNum',
      key: 'storeNum',
      align: 'center',
      width: 130,
    },
    {
      title: '订单编码',
      dataIndex: 'orderCode',
      key: 'orderCode',
      align: 'center',
      width: 180,
    },
    {
      title: '操作人',
      dataIndex: 'operationUserName',
      key: 'operationUserName',
      align: 'center',
      width: 130,
    },
    {
      title: '操作时间',
      dataIndex: 'operationTime',
      key: 'operationTime',
      align: 'center',
      width: 180,
    },
  ]

  const dataQty = computed(() => {
    return orderLogData.value.reduce((sum, e) => sum + Number(e.quantity || 0), 0)
  })

  const orderLogData = ref<OrderLogVO[]>([])
  const orderLogColumns = [
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      key: 'operation',
      align: 'center',
    },
    {
      title: '下单人',
      dataIndex: 'orderUserName',
      key: 'orderUserName',
      align: 'center',
      width: 100,
    },
    {
      title: '寄件人',
      dataIndex: 'senderName',
      key: 'senderName',
      align: 'center',
      width: 100,
    },
    {
      title: '收件人',
      dataIndex: 'consigneeName',
      key: 'consigneeName',
      align: 'center',
      width: 100,
    },
    {
      title: '收件人电话',
      dataIndex: 'consigneeTel',
      key: 'consigneeTel',
      align: 'center',
      width: 140,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      align: 'center',
      width: 100,
    },
    {
      title: '在途订单',
      dataIndex: 'afloatStatus',
      key: 'afloatStatus',
      align: 'center',
      width: 80,
    },
    {
      title: '销售数量',
      dataIndex: 'quantity',
      key: 'quantity',
      align: 'center',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 180,
    },
  ]

  const orderLogSo = reactive<OrderLogSO>({
    productId: '',
    orderStatus: '',
    startTime: '',
    endTime: '',
  })

  let productBo = reactive<ProductBO>({
    id: undefined,
    productName: undefined,
    limitTime: undefined,
    storeNum: undefined,
    price: undefined,
    remark: undefined,
    afloatStatus: '0',
  })

  let data = ref<ProductVO[]>([])
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 15,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
    showTotal: (total) => {
      return `共 ${total} 条`
    },
  })
  const pageParam = computed(() => ({
    query: recordSo,
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))
  let recordSo = reactive<ProductSo>({
    keyword: '',
    sortField: '',
    sortType: '',
    afloatStatus: '',
  })
  onMounted(() => {
    list()
  })

  async function list() {
    loading.value = true
    const res = await pageProduct(pageParam.value)
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  function handleTableChange(page, filters, sorter) {
    console.log('change')
    console.log('Various parameters', sorter)
    sortedInfo.value = sorter
    pagination.value.current = page.current
    recordSo.sortField = sorter.field
    recordSo.sortType = sorter.order
    list()
  }

  const handleAdd = () => {
    createMode.value = true
    nextTick(() => {
      formRef.value?.resetFields()
    })
    open.value = true
  }

  const handleEdit = async (record) => {
    await watchProduct(record.id)
    const current = await currentProduct(record.id)
    currentProductId.value = record.id
    createMode.value = false
    productBo.id = record.id
    productBo.productName = current.productName
    productBo.limitTime = current.limitTime
    productBo.storeNum = current.storeNum
    productBo.remark = current.remark
    productBo.afloatStatus = current.afloatStatus + ''

    open.value = true
  }

  const handleSubmit = async () => {
    submitLoading.value = true
    try {
      await formRef.value?.validateFields()
      productBo.afloatStatus = Number(productBo.afloatStatus)
      if (createMode.value) {
        createProduct(productBo)
          .then((res) => {
            if (res) {
              open.value = false
              message.success('创建成功')
              list()
            } else {
              message.error('创建失败')
            }
          })
          .finally(() => {
            submitLoading.value = false
          })
      } else {
        updateProduct(productBo)
          .then((res) => {
            if (res) {
              open.value = false
              message.success('修改成功')
            } else {
              message.error('修改失败')
            }
          })
          .catch((error) => {
            if (error.message === '产品变更') {
              message.error('产品信息可能已发生变更，请重新修改')

              open.value = false
            }
          })
          .finally(() => {
            handleCloseUpdateProduct()
            submitLoading.value = false
          })
      }
    } catch (errorInfo) {
      submitLoading.value = false
      message.error('提交失败，请检查表单项')
      console.log('Failed:', errorInfo)
    }
  }

  const handleDelete = (record) => {
    deleteProduct(record.id)
      .then((res) => {
        if (res) {
          message.success('删除成功')
        }
      })
      .finally(() => {
        reload()
      })
  }

  const logPagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })
  const logPageParam = computed(() => ({
    query: logSo,
    current: logPagination.value?.current,
    size: logPagination.value?.pageSize,
  }))
  let logSo = reactive<ProductLogSO>({
    productId: '',
  })

  const handleLog = (record) => {
    logSo.productId = record.id
    productLogData.value = []
    logPagination.value.total = 0
    logPagination.value.current = 1

    pageProductLog()
    // pageProductLogApi(logPageParam.value).then((res) => {
    //   productLogData.value = res.records
    //   productLogVisible.value = true
    // })
    productLogVisible.value = true
  }

  const pageProductLog = () => {
    pageProductLogApi(logPageParam.value).then((res) => {
      console.log('pageProductLogApi res', res)
      productLogData.value = res.records
      logPagination.value.total = Number(res.total)
      logPagination.value.current = Number(res.current)
      // logPagination.value.total = res.total
    })
  }

  const handleProductLogChange = (page) => {
    logPagination.value.current = page.current
    pageProductLog()
  }

  const reload = () => {
    pagination.value.current = 1
    list()
  }
  const exportStore = async () => {
    exportStoreApi(recordSo).then((export_data) => {
      let link = document.createElement('a')
      let blogw = new Blob([export_data], { type: 'application/vnd.ms-excel;charset=utf-8' })
      let objectUrl = window.URL.createObjectURL(blogw)
      link.href = objectUrl
      let file_name = `库存明细 - ${moment().format('YYYY-MM-DD HH:mm:ss')}.xlsx`
      link.download = file_name
      link.click()
      window.URL.revokeObjectURL(objectUrl)
    })
  }

  const handleOrderLog = (record) => {
    orderLogSo.productId = record.id
    orderLog(orderLogSo)
      .then((res) => {
        orderLogData.value = res
      })
      .then(() => {
        currentProductName.value = record.productName
        orderLogVisible.value = true
      })
  }

  const reloadLog = () => {
    orderLogSo.startTime = orderTimeRange.value?.[0]
    orderLogSo.endTime = orderTimeRange.value?.[1]
    orderLog(orderLogSo).then((res) => {
      orderLogData.value = res
    })
  }

  const exportOrderLog = () => {
    orderLogSo.startTime = orderTimeRange.value?.[0]
    orderLogSo.endTime = orderTimeRange.value?.[1]
    exportLogByProduct(orderLogSo).then((export_data) => {
      let link = document.createElement('a')
      let blogw = new Blob([export_data], { type: 'application/vnd.ms-excel;charset=utf-8' })
      let objectUrl = window.URL.createObjectURL(blogw)
      link.href = objectUrl
      let file_name = `订单明细 - ${
        currentProductName.value ? currentProductName.value : '产品'
      } - ${moment().format('YYYY-MM-DD HH:mm:ss')}.xlsx`
      link.download = file_name
      link.click()
      window.URL.revokeObjectURL(objectUrl)
    })
  }

  const handleCloseUpdateProduct = async () => {
    console.log('handleCloseUpdateProduct')
    if (createMode.value == false) {
      await unwatchProduct(currentProductId.value)
      currentProductId.value = undefined
      reload()
    }
  }
</script>
<style lang="scss" scoped>
  .wrap {
    &-table {
      margin-top: 16px;
    }
  }
</style>
